package com.zaixiandiancan.xia.Controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.JsonObject;
import com.zaixiandiancan.xia.entity.Goods;
import com.zaixiandiancan.xia.entity.Gtypes;
import com.zaixiandiancan.xia.entity.Order;
import com.zaixiandiancan.xia.entity.Qrcode;
import com.zaixiandiancan.xia.service.GoodsService;
import com.zaixiandiancan.xia.service.OrderService;
import com.zaixiandiancan.xia.service.QrcodeService;
import com.zaixiandiancan.xia.util.BaiduFyUtil;
import com.zaixiandiancan.xia.util.PrintTscUtil;
import com.zaixiandiancan.xia.util.QRCodeUtil;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@CrossOrigin
public class IndexController {

	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private QrcodeService qrcodeService;

	// cookie中购物车键
	private final static String CART_COOKIE = "cart_cookie";
	// 生成二维码URL
	private final static String CODE_URL = "www.zaixiandiancan.com:81";

	Map<String, Object> map = new HashMap<>();

	@RequestMapping(value = "/")
	public String index() {
		return "main";
	}

	@RequestMapping(value = "/main")
	public String index2() {
		return "main";
	}

	private Goods goods = null;

	@RequestMapping(value = "/getGoods", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> searchGoods(@RequestBody Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) {
		map.clear();
		if (goods == null) {
			goods = new Goods();
		}
		Map<String, Object> map = new HashMap<>();
		if (params.get("world_type") != null) {
			String world_type = params.get("world_type").toString();
			System.out.println(world_type);
			if ("".equals(world_type)) {
				map.put("code", -1);
				return map;
			}
			map.put("world_type", world_type);
		}
		// if (params.get("page").equals("goods")) {
		// map.put("world_type", "cn");
		// }

		List<Goods> g_list = new ArrayList<>();

		List<Gtypes> t_list = new ArrayList<>();
		try {
			g_list = goodsService.searchGoods(map);
			// if(params.get("g_type")!=null){
			// g_list = goodsService.searchGoodsByType(params.get("g_type")+"");
			// }
			List<Goods> list = getCartInCookie(response, request);
			map.put("code", 0);
			map.put("message", g_list);
			if (list != null && list.size() > 0) {
				map.put("cookie", list);
			} else {
				map.put("cookie", null);
			}
			t_list = goodsService.searchTypes();
			map.put("types", t_list);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			map.put("code", 1);
		}
		return map;
	}

	@RequestMapping(value = "/addGoods", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addGoods(@RequestBody Goods goods, HttpServletRequest request,
			HttpServletResponse response) {
		map.clear();
		try {
			if (goods != null) {
				boolean b = goodsService.addGoods(goods);
				// boolean b = true;
				if (b) {
					map.put("code", 0);
				} else {
					map.put("code", 1);
				}
			} else {
				map.put("code", -1);
			}
		} catch (Exception e) {
			map.put("code", 1);
		}
		return map;
	}

	// @RequestMapping(value = "/fy", method = RequestMethod.POST)
	@RequestMapping("fy")
	@ResponseBody
	public Map<String, Object> fy(String name, HttpServletRequest request, HttpServletResponse response) {
		System.out.println(name);
		map.clear();
		map.put("cn", name);
		try {
			map.put("zh", BaiduFyUtil.main(name, "zh"));
			map.put("en", BaiduFyUtil.main(name, "en"));
			map.put("jp", BaiduFyUtil.main(name, "jp"));
			map.put("ko", BaiduFyUtil.main(name, "kor"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return map;

	}

	@RequestMapping(value = "/addTypes", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addTypes(@RequestBody Gtypes types, HttpServletRequest request,
			HttpServletResponse response) {
		map.clear();
		try {
			if (goods != null) {
				boolean b = goodsService.addTypes(types);
				// boolean b = true;
				if (b) {
					map.put("code", 0);
				} else {
					map.put("code", 1);
				}
			} else {
				map.put("code", -1);
			}
		} catch (Exception e) {
			map.put("code", 1);
		}
		return map;
	}

	@RequestMapping(value = "/getPay")
	public String getPay() {
		return "end";
	}

	/**
	 *
	 * @param params
	 *            {g=[{id=1, num=2}, {id=2, num=3}], t=2}
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getPays", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getPays(@RequestBody Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) {
		map.clear();
		try {
			Order order = null;
			List<Order> orderList = new ArrayList<>();

			List list = (List) params.get("g");
			Integer t_num = (int) params.get("t");
			String c_time = Calendar.getInstance().getTimeInMillis() + "";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			String o_time = df.format(new Date());
			if (list.size() <= 0) {
				map.put("code", -1);
				return map;
			}
			for (int i = 0; i < list.size(); i++) {
				order = new Order();
				Integer id = (int) ((HashMap) list.get(i)).get("id");
				Integer num = (int) ((HashMap) list.get(i)).get("num");
				order.setG_id(id);
				order.setG_num(num);
				order.setC_time(c_time);
				order.setO_time(o_time);
				order.setT_num(t_num);

				orderList.add(order);
			}
			orderService.addOrder(orderList);
			map.put("code", 0);
			map.put("o_time", o_time);
			map.put("c_time", c_time);
		} catch (Exception e) {
			System.out.println("fuck"+e.getMessage());
			map.put("code", 1);
		}
		return map;
	}

	@RequestMapping(value = "/getOrders")
	@ResponseBody
	public Map<String, Object> getOrders(@RequestBody Map<String, Object> params) {
		map.clear();
		try {
			Order order = new Order();
			String c_time = params.get("c_time").toString().equals("-1") ? null : params.get("c_time").toString();
			order.setC_time(c_time);
			List<Map> orderList = orderService.searchOrder(order);
			if (orderList.size() <= 0) {
				map.put("code", -1);
				return map;
			}
			map.put("code", 0);
			map.put("orders", orderList);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			map.put("code", 1);
		}
		return map;
	}

	// 打印
	@RequestMapping(value = "/printOrder")
	public Map<String, Object> printOrder(HttpServletRequest request) {
		map.clear();
		try {
			String id = request.getParameter("id");
			Order order = new Order();
			order.setId(Integer.parseInt(id));
			List<Map> orderList = orderService.searchOrder(order);
			if (orderList.size() <= 0) {
				map.put("code", -1);
				return map;
			}
			PrintTscUtil.printBoxCode(orderList.get(0));
			map.put("code", 0);
			map.put("orders", orderList);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			map.put("code", 1);
		}
		return map;
	}

	// 清空购物车
	@RequestMapping(value = "/cleanCookie", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> cleanCookie(HttpServletResponse response, HttpServletRequest request) {
		map.clear();
		// 获取名为"cart"的cookie
		Cookie cookie = getCookie(request);
		if (cookie == null) {
			map.put("code", 1);
			return map;
		}
		// 设置寿命为0秒
		cookie.setMaxAge(0);
		// 设置路径
		cookie.setPath("/");
		// 设置cookie的value为null
		cookie.setValue(null);
		// 更新cookie
		response.addCookie(cookie);
		map.put("code", 0);
		return map;
	}

	// 添加购物车
	@RequestMapping(value = "/getCookie", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getCookies(@RequestBody Map<String, Object> params, HttpServletResponse response,
			HttpServletRequest request) {
		// System.out.println(setting);
		map.clear();
		// 获取购物车Cookie
		try {
			List<Goods> list = getCartInCookie(response, request);
			Cookie cookie = null;
			Object good = params.get("good");
			HashMap g_map = (HashMap) good;
			Goods goods = new Goods();
			goods.setId(Integer.parseInt(g_map.get("id").toString()));
			String setting = params.get("setting").toString();
			if (list.size() <= 0) {
				if (getCookie(request) == null) {
					goods.setG_name(g_map.get("g_name").toString());
					goods.setG_price(g_map.get("g_price").toString());
					goods.setG_num(Integer.parseInt(g_map.get("g_num").toString()));
					goods.setCookie_num(
							g_map.get("cookie_num") != null ? Integer.parseInt(g_map.get("cookie_num").toString()) : 1);
					goods.setG_con(g_map.get("g_con").toString());
					goods.setG_type(Integer.parseInt(g_map.get("g_type").toString()));
					list.add(goods);

				} else {
					cookie = getCookie(request);
				}
			} else {
				int g_num = 0;
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).getId() == goods.getId()) {
						g_num++;
						if ("add".equals(setting)) {
							list.get(i).setCookie_num(list.get(i).getCookie_num() + 1);
						} else if ("del".equals(setting) && list.get(i).getCookie_num() > 0) {
							int con = list.get(i).getCookie_num() - 1;
							list.get(i).setCookie_num(con > 0 ? con : 0);
							if (list.get(i).getCookie_num() <= 0) {
								list.remove(i);
							}
						}
					}
				}
				if (g_num <= 0 && "add".equals(setting)) {
					goods.setG_name(g_map.get("g_name").toString());
					goods.setG_price(g_map.get("g_price").toString());
					goods.setG_num(Integer.parseInt(g_map.get("g_num").toString()));
					goods.setCookie_num(
							g_map.get("cookie_num") != null ? Integer.parseInt(g_map.get("cookie_num").toString()) : 1);
					goods.setG_con(g_map.get("g_con").toString());
					goods.setG_type(Integer.parseInt(g_map.get("g_type").toString()));

					list.add(goods);
				}

			}
			if (list.size() > 0) {
				cookie = new Cookie(IndexController.CART_COOKIE, makeCookieValue(list));
				cookie.setPath("/");// 设置在该项目下都可以访问该cookie
				cookie.setMaxAge(60 * 30);// 设置cookie有效时间为30分钟
				response.addCookie(cookie);// 添加cookie
				map.put("code", 0);
				map.put("message", list);
			} else {
				map.put("code", -1);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			map.put("code", 1);
		}
		return map;
	}

	// 从cookie中获取购物车信息
	public static Cookie getCookie(HttpServletRequest request) {
		Cookie[] goods_cart = request.getCookies();
		Cookie c = null;
		if (goods_cart != null) {
			for (Cookie cookie : goods_cart) {
				if (IndexController.CART_COOKIE.equals(cookie.getName())) {
					c = cookie;
				}
			}
		}
		return c;
	}

	/**
	 * 制作cookie所需value
	 *
	 * @param good
	 *            购物车列表
	 * @return 解析为字符串的购物车列表，属性间使用"="相隔，对象间使用"=="相隔
	 */
	public static String makeCookieValue(List<Goods> good) {
		StringBuffer buffer_2st = new StringBuffer();
		for (Goods goods : good) {
			buffer_2st.append(goods.getId() + "=" + goods.getG_type() + "=" + goods.getG_name() + "=" + goods.getG_num()
					+ "=" + goods.getG_con() + "=" + goods.getG_price() + "=" + goods.getCookie_num() + "==");
		}
		return buffer_2st.toString().substring(0, buffer_2st.toString().length() - 2);
	}

	/**
	 * 获取cookie中的购物车列表
	 *
	 * @param response
	 * @param request
	 * @return 购物车列表
	 */
	public static List<Goods> getCartInCookie(HttpServletResponse response, HttpServletRequest request) {
		// 定义空的购物车列表
		List<Goods> items = new ArrayList<Goods>();
		String value_1st = "";
		// 购物cookie
		Cookie cart_cookie = getCookie(request);
		// 判断cookie是否为空
		if (cart_cookie != null) {
			// 获取cookie中String类型的value
			try {
				value_1st = URLDecoder.decode(cart_cookie.getValue(), "utf-8");// 从cookie获取购物车
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// 判断value是否为空或者""字符串
			if (value_1st != null && !"".equals(value_1st)) {
				// 解析字符串中的数据为对象并封装至list中返回给上一级
				String[] arr_1st = value_1st.split("==");
				for (String value_2st : arr_1st) {
					String[] arr_2st = value_2st.split("=");
					Goods item = new Goods();
					item.setId(Integer.parseInt(arr_2st[0])); // 商品id
					item.setG_type(Integer.parseInt(arr_2st[1])); // 商品类型ID
					item.setG_name(arr_2st[2]); // 商品名
					item.setG_price(arr_2st[5]); // 商品市场价格
					item.setG_num(Integer.parseInt(arr_2st[3]));// 商品量
					item.setG_con(arr_2st[4].replace(" ", "+"));// 商品详情
					item.setCookie_num(Integer.parseInt(arr_2st[6]));
					items.add(item);
				}
			}
		}
		return items;

	}

	// 查询二维码
	@RequestMapping(value = "/getCode", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getCode(HttpServletResponse response, HttpServletRequest request) {
		map.clear();
		Qrcode qrcode = new Qrcode();
		QRCodeUtil.getImge("1");
		List<Qrcode> list = qrcodeService.searchCode(qrcode);
		if (list.size() > 0) {
			map.put("code", 0);
			map.put("message", list);
		} else {
			map.put("code", 1);
		}
		return map;
	}

	// 生成二维码
	@RequestMapping(value = "/addCode", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> createCode(@RequestBody Map<String, Object> params, HttpServletResponse response,
			HttpServletRequest request) {
		map.clear();
		// 获取跟目录
		File path = null;
		try {
			path = new File(ResourceUtils.getURL("classpath:").getPath());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if (!path.exists())
			path = new File("");
		File upload = new File(path.getAbsolutePath(), "static/qrcode/");
		if (!upload.exists())
			upload.mkdirs();
		String t_num = params.get("t").toString();
		// String logo = params.get("logo").toString();
		String file_path = upload.getAbsolutePath();

		String b = QRCodeUtil.zxingCodeCreate(IndexController.CODE_URL + "?t=" + t_num, file_path, 500, t_num);
		Qrcode qrcode = null;
		if (!b.equals("")) {
			qrcode = new Qrcode();
			qrcode.setPath(file_path + b);
			qrcode.setT_num(Integer.parseInt(t_num));

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			String o_time = df.format(new Date());
			qrcode.setQ_time(o_time);

			boolean c = qrcodeService.addCode(qrcode);
			if (c) {
				map.put("code", 0);
			} else {
				map.put("code", -1);
			}
		} else {
			map.put("code", 1);
		}
		return map;
	}

	// 查看二维码
	// @ResponseBody
	@RequestMapping(value = "/fileEcho", method = RequestMethod.GET)
	public void fileEcho(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// System.out.println(111);
		// 获取图片存放路径
		// String filePath = params.get("path").toString();
		String id = request.getParameter("path");
		Qrcode qrcode = new Qrcode();
		qrcode.setId(Integer.parseInt(id));
		List<Qrcode> list = qrcodeService.searchCode(qrcode);

		String filePath = list.get(0).getPath();
		if (filePath != null) {
			try {
				FileInputStream fis = new FileInputStream(filePath); // 以byte流的方式打开文件
																		// d:\1.gif
				int i = fis.available(); // 得到文件大小
				byte data[] = new byte[i];
				fis.read(data); // 读数据
				response.setContentType("multipart/form-data");
				response.setContentType("image/*"); // 设置返回的文件类型
				OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
				toClient.write(data); // 输出数据
				toClient.flush();
				toClient.close();
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("图片不存在");
			}
		}
	}

	// 删除二维码
	@RequestMapping(value = "/deleteCode", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteCode(@RequestBody Map<String, Object> params, HttpServletResponse response,
			HttpServletRequest request) {
		map.clear();
		Qrcode qrcode = new Qrcode();
		Integer id = Integer.parseInt(params.get("id").toString());
		qrcode.setId(id);
		boolean b = qrcodeService.deleteCode(qrcode);
		if (b) {
			map.put("code", 0);
		} else {
			map.put("code", 1);
		}
		return map;
	}

	// 二维码下载
	@RequestMapping(value = "/downCode", method = RequestMethod.GET)
	// @ResponseBody
	public String downCode(HttpServletResponse response, HttpServletRequest request) {
		String id = request.getParameter("id");
		Qrcode q = new Qrcode();
		q.setId(Integer.parseInt(id));
		List<Qrcode> list = qrcodeService.searchCode(q);
		String realPath = list.get(0).getPath();

		// 如果文件名不为空，则进行下载
		if (realPath != null) {
			// 设置文件路径

			File file = new File(realPath);

			// 如果文件名存在，则进行下载
			if (file.exists()) {

				// 配置文件下载
				response.setHeader("content-type", "application/octet-stream");
				response.setContentType("application/octet-stream");
				// 下载文件能正常显示中文
				try {
					response.setHeader("Content-Disposition",
							"attachment;filename=" + URLEncoder.encode(realPath, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				// 实现文件下载
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("Download the song successfully!");
				} catch (Exception e) {
					System.out.println("Download the song failed!");
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
}
